package xmlUtil;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/**
 * @AUTHOR : yangfan
 * @DATE : 2017/2/15
 * @TIME : 15:12
 * @VERSION : 1.0
 * @DESC : Java处理xml文件类,载入xml文件,根节点,固定节点值,节点对应属性,节点所有属性,
 */
public class JavaXmlUtil {

    //xml document对象
    private Document doc = null;

    /**
     * 载入xml文件
     */
    public JavaXmlUtil(String filePath) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        InputStream in = JavaXmlUtil.class.getClassLoader().getResourceAsStream(filePath);

        try {
            builder = dbf.newDocumentBuilder();
            doc = builder.parse(in);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取根节点
     *
     * @return 获取根节点
     */
    public Element getRootElement() {
        return doc.getDocumentElement();
    }

    /**
     * 获取根节点名称
     *
     * @return 获取节点名称
     */
    public String getRootElementName() {
        Element root = getRootElement();
        return root.getNodeName();
    }

    /**
     * 查询某节点是否含有子节点
     *
     * @param element 元素
     * @return 是否含有子节点
     */
    public boolean hasChildNodes(Element element) {
        int length = element.getChildNodes().getLength();
        return length > 0;
    }

    /**
     * 通过节点名获取节点
     *
     * @param nodeName 节点名
     * @return NodeList节点结合
     */
    public NodeList getElementByName(String nodeName) {
        return doc.getElementsByTagName(nodeName);
    }

    /**
     * 查询子节点
     *
     * @param node 查询的节点
     * @return NodeList节点集合
     */
    public NodeList getChildNodeList(Node node) {
        return node.getChildNodes();
    }

    /**
     * 通过element查找子节点
     *
     * @param element 查找的元素
     * @return NodeList子节点结合
     */
    public NodeList getChildNodeList(Element element) {
        return element.getChildNodes();
    }

    /**
     * 将xml文件转成字符串
     *
     * @return xml字符串
     */
    public String handleStringToXml() {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = null;
        try {
            t = tf.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }

        t.setOutputProperty("encoding", "utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            t.transform(new DOMSource(doc), new StreamResult(bos));
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return bos.toString();
    }

    /**
     * 将字符串转成xml文件
     *
     * @param xmlString xml字符串
     * @param filePath 生成的文件路径及名称
     */
    public static void handleStringToXml(String xmlString, String filePath) {
        //读取xml字符串
        StringReader sr = new StringReader(xmlString);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        //打开文件流
        File file;
        FileOutputStream outStream = null;
        StreamResult streamResult;

        //转化格式
        Transformer tra = null;
        TransformerFactory tfac = TransformerFactory.newInstance();

        DocumentBuilder builder = null;
        try {
            tra = tfac.newTransformer();
            builder = factory.newDocumentBuilder();
            Document xmlDoc = builder.parse(is);
            DOMSource doms = new DOMSource(xmlDoc);

            //文件流打开
            file = new File(filePath);
            outStream = new FileOutputStream(file);
            streamResult = new StreamResult(outStream);

            //转换
            tra.transform(doms, streamResult);

        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
